import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'

import Login from '../views/Login.vue'
import Register from '../views/Register.vue'
import ProfileIndex from '../views/profile/Index.vue'
import Test from '../views/Test.vue'
import ProfileEdit from '../views/profile/Edit.vue'
import ProfileFollow from '../views/profile/Follow.vue'
import ProfileStar from '../views/profile/Star.vue'
import PostDetail from '../views/PostDetail.vue'
import MoreComment from '../views/MoreComment.vue'
import ProfileComment from '../views/profile/Comment.vue'
import Search from '../views/Search.vue'
import Manage from '../views/Manage.vue'
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  }, {
    path: '/login',
    component: Login
  }, {
    path: '/register',
    component: Register
  }, {
    path: '/profile',
    component: ProfileIndex,
    meta: {
      needAuth: true
    }
  }, {
    path: '/test',
    component: Test,
  }, {
    path: '/edit',
    component: ProfileEdit,
    meta: {
      needAuth: true
    }
  }, {
    path: '/follow',
    component: ProfileFollow
  }, {
    path: "/profilestar",
    component: ProfileStar,
    meta: {
      needAuth: true
    }
  }, {
    path: '/postdetail/:id',
    component: PostDetail
  }, {
    path: '/morecomment/:id',
    component: MoreComment
  }, {
    path: '/comment',
    component: ProfileComment,
    meta: {
      needAuth: true
    }
  }, {
    path: '/search',
    component: Search
  }, {
    path: '/manage',
    component: Manage
  }
]

const router = new VueRouter({
  routes
})
router.beforeEach((to, from, next) => {
  // 如果我进入的地方是个人中心，要先判断token是否存在
  // 1.方法一
  // if (to.path == '/profile' || to.path == '/edit') {
  // 2.方法二
  // 将需要校验的页面配置成一个数组
  // const pagesNeedAuth = [
  //   '/profile',
  //   '/edit'
  // ]
  // if (pagesNeedAuth.indexOf(to.path) > 0) {
  // 3.方法三
  // 第三种判断方法, 可以给页面路由配置设置 meta, 在这里判断即可
  if (to.meta.needAuth) {
    if (localStorage.getItem('token')) {
      //存在就放行
      return next()
    } else {
      // return router.push('/login')
      // 避免相同页面跳回自己的报错
      return router.push('/login').catch(err => { })
    }
  }
  // 其他页面的允许跳转
  return next()
})

export default router
